<template>
  <div v-loading="loading" class="app-container">
    <!--组件引入 -->
    <PageTools :show-before="true">
      <template #before>共{{ total }}条数据</template>
      <template #after>
        <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
        <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
        <el-button size="small" type="primary" @click="isShow=true">新增员工</el-button>
      </template>
    </PageTools>
    <el-card>
      <el-table border="" :data="employerList">
        <el-table-column width="60" align="center" label="序号" type="index" sortable="" :index="customIndex" />
        <el-table-column
          label="图片"
          width="180px"
        >
          <template v-slot="scope">
            <img v-fixImg :src="scope.row.staffPhoto" alt="" class="avatar">
          </template>
        </el-table-column>
        <el-table-column
          label="
          姓名"
          prop="username"
          sortable=""
        />
        <el-table-column label="工号" prop="workNumber" sortable="" />
        <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatStyle" sortable="" />
        <el-table-column label="部门" prop="departmentName" sortable="" />
        <el-table-column label="手机号" prop="mobile" sortable="" />
        <el-table-column label="入职时间" sortable="">
          <template slot-scope="scope">
            {{ scope.row.timeOfEntry |getNowFormatDate }}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" prop="enableState" sortable="">
          <template v-slot="scope">
            <el-switch v-model="scope.row.enableState" :active-value="1" disabled :inactive-value="2" />
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable="" width="280">
          <template v-slot="{row}">
            <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination :total="total" :page-size="pageConfig.size" layout="prev, pager, next" @current-change="handlePage" />
      </el-row>
    </el-card>
    <AddEmployees :is-show="isShow" @closeFn="closeFn" @reloadPage="getEmployerList" />
    <AssignRole ref="assignRole" :is-show.sync="isShowRole" />
  </div>
</template>

<script>
import { getEmployer, delEmployer } from '@/api/employees'
// 引入excel导出
import { export_json_to_excel } from '@/vendor/Export2Excel'
import AddEmployees from './components/add-employees.vue'
// 引入枚举数据
import EmployeeEnum from '@/api/constant/employees'
import AssignRole from './components/assign-role.vue'
// 时间处理过滤器
import { formatDate } from '@/filters'
export default {
  components: { AddEmployees, AssignRole },
  data() {
    return {
      pageConfig: {
        page: 1,
        size: 5
      },
      // 加载
      loading: false,
      total: 1,
      // 员工列表
      employerList: [],
      // 对话框是否显示
      isShow: false,
      isShowRole: false
    }
  },
  async created() {
    // 调用获取信息接口
    await this.getEmployerList()
  },
  methods: {
    // 封装获取员工信息结构
    async getEmployerList() {
      this.loading = true
      const { total, rows } = await getEmployer(this.pageConfig)
      // 通过map方法可以修改原本的数据
      this.employerList = rows.map(item => {
        return { ...item,
          timeOfEntry: new Date().toString(),
          enableState: 1 }
      })
      this.total = total
      this.loading = false
      console.log('员工列表', this.employerList)
    },
    // 自定义索引
    customIndex(index) {
      return (this.pageConfig.page - 1) * this.pageConfig.size + index + 1
    },
    handlePage(val) {
      // 分页功能
      this.pageConfig.page = val
      this.getEmployerList()
    },
    // 格式化表格内容
    formatStyle(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // hireType是一个数组，find方法筛选出来第一个通过条件的元素  找不到返回undefined，所以要加入短路运算，先保证存在，否则用undefined.属性  会报错
      const res = EmployeeEnum.hireType.find(item => {
        return item.id === cellValue
      })
      // console.log(res) //返回整个对象
      return res ? res.value : '未知'
    },
    // 删除功能
    async delFn(id) {
      try {
        // 二次确认
        await this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        // 发送请求
        await delEmployer(id)
        // 提示
        this.$message('删除成功')
        // 重新渲染
        this.getEmployerList()
      } catch (error) {
        console.log(error)
      }
    },
    // 弹窗关闭
    closeFn() {
      this.isShow = false
    },
    // 导出excel
    async  exportExcel() {
      // 获取全部员工列表
      const { rows } = await getEmployer({
        page: 1, size: this.total
      })
      // console.log('全部员工列表', rows)
      // 字典
      const dicts = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 处理传入excel的数据
      // 表头header,其实是dicts的键，并且需要数组的形式---Object.keys方法
      const header = Object.keys(dicts)
      console.log(header)
      // 表格内容data,需要数组套数组的方法[[表格每一行的内容]]   遍历全部员工列表，将键变为英文，值不变，map方法会返回一个新数组,如果里面也有一个数组，就是数组套数组的形式
      const data = rows.map(user => {
        const arr = []
        for (const keys in dicts) {
          // 数据需要特殊处理  日期、聘用形式
          if (dicts[keys] === 'formOfEmployment') {
            const val = user[dicts[keys]]
            // find方法查找第一个通过测试的值
            const res = EmployeeEnum.hireType.find(item => item.id === val)
            arr.push(res ? res.value : '未知')
          } else if (dicts[keys] === 'timeOfEntry' || dicts[keys] === 'correctionTime') {
            const val = user[dicts[keys]]
            arr.push(formatDate(val))
          } else {
            // 拿到数组的每个属性推入到数组中,比如dicts[keys]--mobile   通过user[mobile]就可以获取到对象的值
            arr.push(user[dicts[keys]])
          }
        }
        return arr
      })
      console.log('处理后的数据', data)
      // 导出数据
      export_json_to_excel({
        header,
        data
      })
    },
    // 分配角色
    async assignRole(id) {
      // 回显数据
      await this.$refs.assignRole.getRoleById(id)
      this.isShowRole = true
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar{
  width: 160px;
  height: 80px;
  object-fit: cover;
}
</style>
